import React, { useState, useRef, useEffect } from 'react'
import { message, Modal, Space, Spin, Typography } from 'antd'
import { EditableProTable, ActionType, ProColumns } from '@ant-design/pro-table'
import { observer } from '@formily/react'
import { getPageList, savePageList } from '../service/schema'
import moment from 'moment'
import { loadInitialSchema } from '../service/schema'
import { useOperation } from '@designable/react'

// 页面配置数据类型定义
export interface PageConfig {
  id?: string
  fileUrl: string
  pageName: string
  description?: string
  createTime?: string
  updateTime?: string
}

// PageManagementWidget props接口
export interface PageManagementWidgetProps {
  visible?: boolean
  onClose?: () => void
}

export const PageManagementWidget: React.FC<PageManagementWidgetProps> =
  observer(({ visible = true, onClose }) => {
    const actionRef = useRef<ActionType>()
    const [pageData, setPageData] = useState<PageConfig[]>([])
    const [loading, setLoading] = useState(false)
    const operation = useOperation('form')

    // 加载页面数据
    const loadPageData = async () => {
      try {
        setLoading(true)
        const data = await getPageList()
        // 确保每个记录都有唯一的id
        const dataWithId = data.map((item: any, index: number) => ({
          ...item,
          id: index,
        }))
        setPageData(dataWithId)
      } catch (error) {
        message.error('加载页面数据失败，请重试')
      } finally {
        setLoading(false)
      }
    }

    // 组件挂载时加载数据
    useEffect(() => {
      if (visible) {
        loadPageData()
      }
    }, [visible])

    // 生成唯一ID
    const generateId = () => {
      return Date.now().toString(36) + Math.random().toString(36).substr(2)
    }

    // 处理删除页面（用于操作列的删除按钮）
    const handleDelete = async (index: number) => {
      const record = pageData[index]
      Modal.confirm({
        title: '确认删除',
        content: `确定要删除页面 "${
          record?.pageName || '未知页面'
        }" 吗？删除后无法恢复。`,
        okText: '确认删除',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          try {
            const newData = pageData.filter((_, i) => i !== index)
            await savePageList(newData)
            setPageData(newData)
            message.success('页面配置删除成功！')
          } catch (error) {
            message.error('删除页面失败，请重试')
          }
        },
      })
    }

    // 处理编辑记录
    const handleEditRecord = (record: PageConfig) => {
      // 触发EditableProTable的编辑模式
      if (actionRef.current) {
        actionRef.current.startEditable(record.id)
      }
    }

    // 切换画板到指定页面的schema，仅替换 hash 中的 page 参数
    const handleContentEdit = (record: PageConfig) => {
      if (!record?.pageName) return
      const currentHash = window.location.hash || ''
      const [hashPath, hashQuery = ''] = currentHash
        .replace(/^#/, '')
        .split('?')
      const params = new URLSearchParams(hashQuery)
      params.set('page', record.pageName)
      const newHash = `${hashPath}?${params.toString()}`
      window.location.hash = `#${newHash}`
      loadInitialSchema()
      requestAnimationFrame(() => {
        operation?.selection?.select(operation?.tree)
      })
      onClose?.()
    }

    // EditableProTable列定义
    const columns: ProColumns<PageConfig>[] = [
      {
        title: '页面路径',
        dataIndex: 'pageName',
        formItemProps: {
          rules: [
            { required: true, message: '请输入页面名称' },
            { min: 2, message: '页面名称至少2个字符' },
            { max: 50, message: '页面名称不能超过50个字符' },
          ] as any,
        },
        ellipsis: true,
      },
      {
        title: '文件URL',
        dataIndex: 'fileUrl',
        formItemProps: {
          rules: [
            { required: true, message: '请输入文件URL' },
            { type: 'url', message: '请输入有效的URL地址' },
            {
              pattern: /\.(json|js|ts|tsx|jsx)$/i,
              message: '文件URL应该指向JSON、JS或TS文件',
            },
          ] as any,
        },
        ellipsis: true,
      },
      {
        title: '描述',
        dataIndex: 'description',
        formItemProps: {
          rules: [{ max: 200, message: '描述不能超过200个字符' }] as any,
        },
        width: 200,
        ellipsis: true,
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        width: 200,
        editable: () => false,
        ellipsis: true,
      },
      {
        title: '操作',
        valueType: 'option',
        width: 200,
        fixed: 'right',
        render: (_, record: PageConfig, index: number) => {
          return (
            <Space>
              <Typography.Link onClick={() => handleContentEdit(record)}>
                内容编辑
              </Typography.Link>
              <Typography.Link onClick={() => handleEditRecord(record)}>
                编辑
              </Typography.Link>
              <Typography.Link
                type="danger"
                onClick={() => handleDelete(index)}
              >
                删除
              </Typography.Link>
            </Space>
          )
        },
      },
    ]

    return (
      <Modal
        title="页面管理"
        open={visible}
        onCancel={onClose}
        width="90%"
        footer={null}
        destroyOnClose
      >
        <div style={{ padding: '16px', userSelect: 'text' }}>
          <Spin spinning={loading}>
            <EditableProTable<PageConfig>
              actionRef={actionRef}
              columns={columns}
              value={pageData}
              rowKey="id"
              recordCreatorProps={{
                record: () => ({
                  id: generateId(),
                  pageName: '',
                  fileUrl: '',
                  description: '',
                  updateTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                }),
              }}
              editable={{
                type: 'multiple',
                onSave: async (key, row) => {
                  try {
                    let newPageData = JSON.parse(JSON.stringify(pageData))
                    const currentItemIndex = newPageData.findIndex(
                      (item) => item.id === key
                    )
                    if (currentItemIndex > -1) {
                      newPageData[currentItemIndex] = {
                        ...newPageData[currentItemIndex],
                        ...row,
                        updateTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                      }
                    } else {
                      newPageData.push({
                        ...row,
                        id: key,
                        updateTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                      })
                    }

                    setPageData(newPageData)
                    await savePageList(newPageData)
                    message.success('保存成功！')
                  } catch (error) {
                    message.error('保存页面失败，请重试')
                  }
                },
                actionRender: (row, config, dom) => [dom.save, dom.cancel],
              }}
              scroll={{ x: 1000 }}
              size="small"
              bordered
            />
          </Spin>
        </div>
      </Modal>
    )
  })

// 默认导出
export default PageManagementWidget
